import { SendOutlined, LoadingOutlined, UserOutlined, StopOutlined } from '@ant-design/icons';
import {
  Input,
  List,
  Avatar,
  Button,
  Skeleton,
  Spin,
  Empty,
  Typography,
  message,
  Checkbox,
  Badge,
} from 'antd';
import { customAlphabet } from 'nanoid';
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import ReactMarkdown from 'react-markdown';
import { useContextSelector } from 'use-context-selector';
import { SvgIcon } from '@/components/icon';

import DefaultRobot from '@/assets/icons/ic_rj_robot.svg';
import { useParams } from '@/router/hooks';
import { useUserInfo } from '@/store/userStore';
import userStore from '@/store/userStore';
import { useThemeToken } from '@/theme/hooks';

import { ChatContext } from '../context';
import { defaultChatData, SseResponseEventEnum, Quote } from '../tools/constants';
import { streamFetch, StreamResponseType } from '../tools/fetch';
import { getNanoid } from '../tools/tools';

import type { StartChatFnProps, InitChatResponse } from '../tools/constants';
import useWindowWidth from '@/hooks/event/use-window-width';
// import Dictaphone from './Dictaphone';
import FunasrRecorder from './FunasrRecorder';
import Dictaphone from './Recorder';

import MessageList from './MessageList';
import MessageSendInputSmart from './MessageSendInputSmart';
import MessageSendInputHome from '@/pages/homepage/components/MessageSendInputHome';

import { useRouter } from '@/router/hooks';
import appService from '@/api/services/appService';

import dayjs from 'dayjs';

import useInitialize from '@/hooks/event/use-initialize';
import chatService from '@/api/services/chatService';

const { VITE_LOGIN_PAGE: LOGINPAGE } = import.meta.env;
const { VITE_AUTH_FLAG: AUTHFLAG } = import.meta.env;
const authFlag = AUTHFLAG === 'true' ? true : false;

import { useConfig, useAppInfo, useConfigActions } from '@/store/configStore';
import { resetCookie } from '@/pages/auth/authUtils';
import { none } from 'ramda';

import { useLocation } from 'react-router-dom';
import { useChatId } from '@/store/configStore';

import { BrandingEnum } from '@/common';

import { useIsDeepMode } from '@/store/chatStore';
import { useUpdate } from 'ahooks';
import { ChatEventType } from '@/types/chat';
import { ResultEnum } from '@/types/enum';
import { useOrchestrationStore } from '@/store/orchestrationStore';

const { TextArea } = Input;

interface Message {
  text: string;
  isUser: boolean;
  loading?: boolean;
  loadingText?: string;
  chatId?: string;
  dataId?: string;
  ts?: number;
  quote?: Quote[];
  isSurvey?: boolean;
  isTextGenerate?: boolean;
}

interface GuessQuestion {
  id: string;
  content: string;
}

interface ChatBoxProps {
  initChatId: string;
  initialMessages?: Message[]; // Define the prop for initial messages as optional
  reHisList;
  setListLeft;
  listLeft;
  isChatInitialized;
  setIsChatInitialized;
  isTest: boolean;
  url?: string;
  onStartChat?: (e: StartChatFnProps) => Promise<
    StreamResponseType & {
      isNewChat?: boolean;
    }
  >;
}

const ChatBox: React.FC<ChatBoxProps> = ({
  isTest,
  initialMessages = [],
  initChatId = '',
  reHisList,
  setListLeft,
  listLeft,
  setIsChatInitialized,
  isChatInitialized,
  url,
  onStartChat,
}) => {
  const update = useUpdate();
  const { title } = useConfig();
  const isDeepMode = useIsDeepMode();
  const [messages, setMessages] = useState<Message[]>(initialMessages);
  const [isInputTyping, setIsInputTyping] = useState(false);
  const [chatNanoId, setChatNanoId] = useState('');
  const [robotAvatar, setRobotAvatar] = useState(DefaultRobot);
  const [isMessageSend, setIsMessageSend] = useState(false);
  const { isPc } = useWindowWidth();
  const [messageApi, contextHolder] = message.useMessage();
  const [voice, setVoice] = useState(false);
  const [isSurveyFlag, setIsSurveyFlag] = useState(true);
  const [isTextGenerate, setIsTextGenerate] = useState(false);

  const { isRuiLogin } = useInitialize();
  const surveyDurationDay = 15;
  const surveySample = 10;
  const inactivityTimer = useRef<NodeJS.Timeout | undefined>(undefined);
  // const surveySample = Math.floor(Math.random()*(20-10+1)) + 10; // 10~20的随机数

  // const thinkFilter = [
  //   'RAG对话', // AI 对话
  //   '知识库搜索',
  //   '安全内容审核',
  //   '内容安全审核',
  //   '问题优化', // 问题思考
  //   '问题分类', // 问题思考
  // ];

  const thinkFilterMap = {
    RAG对话: '大模型对话', // AI 对话
    'RAG对话-R1': '大模型对话', // AI 对话
    'RAG对话-QWEN': '大模型对话', // AI 对话
    知识库搜索: '知识库搜索',
    安全内容审核: '安全内容审核',
    内容安全审核: '内容安全审核',
    问题优化: '问题理解',
    问题分类: '问题理解',
  };

  const { id: appId, share_id: shareId } = useConfig();

  const location = useLocation();
  const queryParams = new URLSearchParams(location.search);
  const appIdTest = queryParams.get('appId') || '';
  const shareIdTest = queryParams.get('shareId') || '';

  const { replace } = useRouter();
  const currentChatId = useChatId();

  const appInfoInitialize = useAppInfo();

  // asr
  // const { type, id, sid, did, mid } = useParams();
  const { type, id, sid } = useParams();

  const currentMessageRef = useRef('');
  const thinkListcurrentMessageRef = useRef([]);
  const { username, email, avatar, team } = useUserInfo();
  const { colorBgElevated, borderRadiusLG, boxShadowSecondary, boxShadowTertiary, colorPrimary } =
    useThemeToken();

  const {
    event$,
    actId,
    // shareId,
    datasetId,
    streamUrl,
    mhSessionId,
    isMetaHuman,
    appInfo,
    outLinkUid,
    stopMetaHuman,
    launchMetaHuman,
    setIsMetaHuman,
    setTaskId,
    stopSpeaking,
    setChatId,
    setActId,
    setIsMessageLoading,
    playAudio,
    isMuted,
    isAudioPlaying,
    setChatReport,
  } = useContextSelector(ChatContext, (s) => s);

  const textAreaRef = useRef<HTMLTextAreaElement | null>(null);
  const customVariables = {};
  const appType = 'advanced';

  const [chatData, setChatData] = useState<InitChatResponse>(defaultChatData);

  const { fetchPermitFlag } = useConfigActions();

  const isAnswerEvent = (event: SseResponseEventEnum) =>
    event === SseResponseEventEnum.answer || event === SseResponseEventEnum.fastAnswer;

  const startChat = useCallback(
    async ({
      messages,
      controller,
      chatId,
      generatingMessage,
      variables,
      responseChatItemId,
    }: StartChatFnProps) => {
      fetchPermitFlag();
      const histories = messages.slice(-1);

      const { responseText, responseData } = await streamFetch({
        url: url
          ? url
          : isTest
          ? '/openapi/v1/chat/annotation/test'
          : '/openapi/v1/chat/completions',
        data: {
          messages: histories,
          variables: {
            isPc,
            r1_enabled: isDeepMode,
            industry: appInfoInitialize?.industry_type ? appInfoInitialize?.industry_type : '',
            app: title,
            ...variables,
            ...customVariables,
          },
          shareId: shareId || sid || shareIdTest,
          appId: appId || id || appIdTest,
          chatId,
          responseChatItemId,
          appType,
          outLinkUid,
          mhUrl: streamUrl,
          mhSessionId: `${mhSessionId}`,
        },
        onMessage: generatingMessage,
        abortCtrl: controller,
      });
      return { responseText, responseData };
    },
    [customVariables, shareId, outLinkUid, chatNanoId],
  );

  const [startChatProps, setStartChatProps] = useState<StartChatFnProps | null>(null);
  const [startChatItem, setStartChatItem] = useState({});

  const handleInterrupt = async () => {
    if (startChatProps?.controller) {
      startChatProps.controller.abort();
      // isMetaHuman && isAudioPlaying && await stopSpeaking()
      isMetaHuman && (await stopSpeaking());
      setIsMessageSend(false);
      setMessages((prevMessages) => {
        const updatedMessages = [...prevMessages];
        const lastIndex = updatedMessages.length - 1;
        if (lastIndex >= 0 && updatedMessages[lastIndex].loading) {
          updatedMessages[lastIndex] = { ...updatedMessages[lastIndex], loading: false };
        }
        return updatedMessages;
      });
      messageApi.info('回答已取消');
    }
  };

  const generateGuessQuestions = () => {
    // 转换当前消息列表为API所需的格式
    // if (messages.length < 2) return; // 至少有一轮对话才生成推荐问题
    setGuessQuestions([]);

    const chatMessages = messages.map((msg) => ({
      role: msg.isUser ? ('user' as const) : ('assistant' as const),
      content: msg.text,
    }));

    // 调用API生成猜你想问的问题
    chatService
      .createQuestionGuide({
        messages: chatMessages,
      })
      .then((response) => {
        console.log('response============', response);
        if (response && Array.isArray(response)) {
          const newGuessQuestions: GuessQuestion[] = response.map((item, index) => ({
            id: String(index + 1),
            content: item,
          }));

          // 更新猜你想问的问题列表
          if (newGuessQuestions.length > 0) {
            setGuessQuestions(newGuessQuestions);
          }
        } else {
          // 如果API调用失败或返回为空，使用默认问题
          setGuessQuestions([]);
        }
      })
      .catch((error) => {
        console.error('获取猜你想问失败:', error);
        // 发生错误时使用默认问题
        setGuessQuestions([]);
      });
  };

  const handleSend = async (question?: string) => {
    if (!(typeof question === 'string')) {
      return;
    }
    if (isMessageSend) {
      return;
    }
    if (isMessageSend && !question) {
      return;
    }
    // isMetaHuman && isAudioPlaying && await stopSpeaking()
    isMetaHuman && (await stopSpeaking());
    playAudio();

    const q = question.trim();

    // console.log(chatId, setChatNanoId)
    const completionChatId = getNanoid();
    if (!chatNanoId) {
      setChatId(completionChatId);
      setChatNanoId(completionChatId);
    }
    currentMessageRef.current = '';
    thinkListcurrentMessageRef.current = [];
    const start = Date.now();
    const responseChatId = getNanoid(24);
    const humanChatId = getNanoid(24);

    const userMessage = {
      text: q,
      isUser: true,
      dataId: humanChatId,
      chatId: chatNanoId ? chatNanoId : completionChatId,
    };
    setMessages((prevMessages) => [...prevMessages, userMessage]);
    // setInputValue('');

    const now = new Date();
    const isoFormattedNow = now.toISOString();

    setStartChatItem({
      _id: completionChatId,
      title: q,
      obj: 'Human',
      // userId: team.userId,
      time: isoFormattedNow,
      id: completionChatId,
    });

    console.log(131231);

    const newStartChatProps: StartChatFnProps = {
      messages: [
        {
          content: q,
          role: 'user',
          dataId: humanChatId,
          chatId: chatNanoId ? chatNanoId : completionChatId,
        },
      ],
      controller: new AbortController(),
      chatId: chatNanoId ? chatNanoId : completionChatId,
      responseChatItemId: responseChatId,
      generatingMessage: (message) => {
        if (message.event == SseResponseEventEnum.error) {
          // console.log('message============', message);
        }
        if (message.event == SseResponseEventEnum.flowNodeStatus) {
          // console.log('message============', message);

          const thoughtItem = {
            title: message.name,
            description: '暂无',
            status: 'success',
          };

          let matchedKeyword = null;

          for (const filterItem of Object.keys(thinkFilterMap)) {
            // if (thoughtItem.title!.includes(filterItem)) {
            //   matchedKeyword = thinkFilterMap?.[thoughtItem?.title];
            //   break;
            // }
            if (thoughtItem.title && thoughtItem.title.startsWith(filterItem)) {
              matchedKeyword = thinkFilterMap[filterItem];
              break;
            }
          }

          if (matchedKeyword) {
            const mappedTitle = matchedKeyword; // 映射为匹配到的关键词

            // 移除已存在的重复条目
            thinkListcurrentMessageRef.current = thinkListcurrentMessageRef.current.filter(
              (item) => item.title !== mappedTitle,
            );

            // 添加新的条目
            thinkListcurrentMessageRef.current.push({ ...thoughtItem, title: mappedTitle });
          }

          setMessages((prevMessages) => {
            const lastMessage = prevMessages[prevMessages.length - 1];

            const newMessage = {
              thinkList: thinkListcurrentMessageRef.current,

              text: currentMessageRef.current,
              isUser: false,
              loading: true,
              chatId: chatNanoId ? chatNanoId : completionChatId,
              dataId: humanChatId,
              loadingText: message.event,
              ts: lastMessage?.ts ? lastMessage?.ts : Date.now() - start,
            };

            // console.log('newMessage===========', newMessage.thinkList, lastMessage.thinkList);

            // Check if the last message is the same as the new message to avoid unnecessary updates
            if (
              lastMessage &&
              lastMessage.text === newMessage.text &&
              lastMessage.thinkList == newMessage.thinkList &&
              lastMessage.loadingText === newMessage.loadingText
            ) {
              return prevMessages;
            }

            if (lastMessage && !lastMessage.isUser) {
              return [...prevMessages.slice(0, -1), newMessage];
            }

            return [
              ...prevMessages,
              {
                thinkList: thinkListcurrentMessageRef.current,
                text: currentMessageRef.current,
                isUser: false,
                loading: false,
                chatId: chatNanoId ? chatNanoId : completionChatId,
                dataId: responseChatId,
                loadingText: message.event,
              },
            ];
          });

          update();
        }
        if (message.event == 'contentViolation') {
          currentMessageRef.current = '' + message.text;
          setMessages((prevMessages) => {
            const lastMessage = prevMessages[prevMessages.length - 1];

            const newMessage = {
              thinkList: thinkListcurrentMessageRef.current,

              text: currentMessageRef.current,
              isUser: false,
              loading: true,
              chatId: chatNanoId ? chatNanoId : completionChatId,
              dataId: humanChatId,
              loadingText: message.event,
              ts: lastMessage?.ts ? lastMessage?.ts : Date.now() - start,
            };

            // Check if the last message is the same as the new message to avoid unnecessary updates
            if (
              lastMessage &&
              lastMessage.text === newMessage.text &&
              lastMessage.loadingText === newMessage.loadingText
            ) {
              return prevMessages;
            }

            if (lastMessage && !lastMessage.isUser) {
              return [...prevMessages.slice(0, -1), newMessage];
            }

            return [
              ...prevMessages,
              {
                thinkList: thinkListcurrentMessageRef.current,

                text: currentMessageRef.current,
                isUser: false,
                loading: false,
                chatId: chatNanoId ? chatNanoId : completionChatId,
                dataId: responseChatId,
                loadingText: message.event,
              },
            ];
          });

          return;
        }

        if (isAnswerEvent(message.event)) {
          currentMessageRef.current += message.text;
          setMessages((prevMessages) => {
            const lastMessage = prevMessages[prevMessages.length - 1];
            // if (lastMessage && !lastMessage.isUser) {
            //   return [
            //     ...prevMessages.slice(0, -1),
            //     {
            //       text: currentMessageRef.current,
            //       isUser: false,
            //       loading: true,
            //       chatId: chatNanoId ? chatNanoId : completionChatId,
            //       dataId: humanChatId,
            //       loadingText: message.event,
            //       ts: lastMessage.ts ? lastMessage.ts : Date.now() - start
            //     },
            //   ];
            // }

            const newMessage = {
              thinkList: thinkListcurrentMessageRef.current,

              text: currentMessageRef.current,
              isUser: false,
              loading: true,
              chatId: chatNanoId ? chatNanoId : completionChatId,
              dataId: humanChatId,
              loadingText: message.event,
              ts: lastMessage?.ts ? lastMessage?.ts : Date.now() - start,
            };

            // Check if the last message is the same as the new message to avoid unnecessary updates
            if (
              lastMessage &&
              lastMessage.text === newMessage.text &&
              lastMessage.loadingText === newMessage.loadingText
            ) {
              return prevMessages;
            }

            if (lastMessage && !lastMessage.isUser) {
              return [...prevMessages.slice(0, -1), newMessage];
            }

            return [
              ...prevMessages,
              {
                thinkList: thinkListcurrentMessageRef.current,

                text: currentMessageRef.current,
                isUser: false,
                loading: false,
                chatId: chatNanoId ? chatNanoId : completionChatId,
                dataId: responseChatId,
                loadingText: message.event,
              },
            ];
          });
        }
      },
      variables: { ...flowVariables },
    };
    setStartChatProps(newStartChatProps);

    try {
      setMessages((prevMessages) => [
        ...prevMessages,
        {
          text: '',
          isUser: false,
          loading: true,
          dataId: humanChatId,
          chatId: chatNanoId ? chatNanoId : completionChatId,
        },
      ]);
      setIsMessageSend(true);

      const responseData = onStartChat
        ? await onStartChat(newStartChatProps)
        : await startChat(newStartChatProps);
      // const responseData = onStartChat ? await onStartChat : await startChat(newStartChatProps);
      setMessages((prevMessages) => {
        const updatedMessages = [...prevMessages];
        const lastIndex = updatedMessages.length - 1;
        if (lastIndex >= 0 && updatedMessages[lastIndex].loading) {
          let quoteList = [];
          const filteredList = responseData?.responseData || [];
          if (filteredList.length > 0) {
            quoteList = filteredList.reduce((acc, item) => {
              return acc.concat(item?.quoteList);
            }, []);
          }

          updatedMessages[lastIndex] = {
            ...updatedMessages[lastIndex],
            loading: false,
            chatId: chatNanoId ? chatNanoId : completionChatId,
            dataId: responseChatId,
            // quote: responseData?.responseData?.[0]?.quoteList || []
            quote: quoteList || [],
          };
        }
        return updatedMessages;
      });
    } catch (error) {
      if (error?.status === ResultEnum.UNAUTHORIZED) {
        error?.message && message.info(error?.message);
        resetCookie();
        userStore.getState().actions.clearUserInfoAndToken();
        return;
      }

      // console.error('An error occurred during chat:', error, error.message);

      // error?.message && message.error(error?.message);

      setMessages((prevMessages) => [
        ...prevMessages.slice(0, -1),
        {
          // text: 'Sorry, an error occurred. Please try again later.',
          thinkList: thinkListcurrentMessageRef.current,
          text: error.message,
          isUser: false,
          loading: false,
          dataId: humanChatId,
          chatId: chatNanoId ? chatNanoId : completionChatId,
        },
      ]);
    } finally {
      setIsMessageSend(false);
    }

    if (textAreaRef.current) {
      // console.log(textAreaRef.current)
      textAreaRef.current?.setSelectionRange(0, 0);
      textAreaRef.current?.focus();
    }

    // isInOrchestrationPage && suggestedQuestions && generateGuessQuestions();
  };

  useEffect(() => {
    setIsMessageLoading(isMessageSend);
  }, [isMessageSend]);

  // useEffect(() => {
  //   if (isMessageSend) {
  //     inactivityTimer && clearTimeout(inactivityTimer.current);
  //   }
  //   if (!isMessageSend && !isSurveyFlag && messages?.length > 2 * surveySample) {
  //     inactivityTimer && clearTimeout(inactivityTimer.current);
  //     inactivityTimer.current = setTimeout(() => {
  //       if (isMessageSend || isSurveyFlag) {
  //         return;
  //       }

  //       setMessages((prevMessages) => {
  //         const newMessages = [...prevMessages];

  //         if (!newMessages[newMessages.length - 1]?.isSurvey) {
  //           newMessages.push({
  //             isUser: false,
  //             text: `您好，您对AI应用的服务满意吗？`,
  //             isSurvey: true,
  //           });
  //         }

  //         return newMessages;
  //       });

  //       setIsSurveyFlag(true);
  //     }, 5000);
  //   }
  //   return () => {
  //     inactivityTimer && clearTimeout(inactivityTimer.current);
  //   };
  // }, [isMessageSend]);

  useEffect(() => {
    // if (!isPc || listLeft.length == 0 || !chatNanoId) {
    //   return
    // }
    if (!isMessageSend) {
      if (messages.length === 0) {
        setActId('');
      } else {
        if (messages.length > 3) {
          return;
        }
        chatNanoId && setActId(chatNanoId);
        if (!isChatInitialized && listLeft.length > 0) {
          // console.log("listLeft============",listLeft ,dayjs(startChatItem.time).format('YYYY-MM-DD'));
          if (dayjs(startChatItem.time).format('YYYY-MM-DD') == listLeft[0].time) {
            setListLeft((pre) => {
              const updatedFirstItem = {
                ...pre?.[0],
                child: [startChatItem, ...pre?.[0]?.child],
              };
              return [updatedFirstItem, ...pre.slice(1)];
            });
          } else {
            const newFirstItem = {
              time: dayjs(startChatItem.time).format('YYYY-MM-DD'),
              child: [startChatItem],
            };
            setListLeft([newFirstItem, ...listLeft]);
          }

          setIsChatInitialized(true);
        }
      }
    }
  }, [isMessageSend]);

  useEffect(() => {
    if (!isMessageSend) {
      if (messages.length === 0) {
        setActId('');
      }
    }
  }, [messages]);

  // useEffect(() => {
  //   if (!isTest && appInfo?.welcome_text && messages.length == 0) {
  //     messages.push({
  //       isUser: false,
  //       text: appInfo?.welcome_text,
  //     });
  //   }
  // }, [appInfo]);

  useEffect(() => {
    if (textAreaRef.current) {
      textAreaRef.current.focus();
    }

    // 是否需要调研
    // id &&
    //   appService.surveyFetch(id).then((res) => {
    //     if (res?.update_time) {
    //       const updateTime = dayjs(res.update_time);
    //       const currentTime = dayjs();
    //       const daysDifference = currentTime.diff(updateTime, 'day');
    //       if (daysDifference < surveyDurationDay) {
    //         setIsSurveyFlag(true); // 已经填写过的不重复填写
    //       }
    //     }
    //   });

    const { state } = location;
    if (state?.msg) {
      setTimeout(() => {
        handleSend(state?.msg);
      }, 100);
    }
  }, []);

  useEffect(() => {
    console.log(initialMessages);
    if (initialMessages.length == 0) {
      if (isMessageSend) {
        handleInterrupt();
        setTimeout(() => {
          setChatId('');
          setChatNanoId('');
          setMessages(initialMessages);
        }, 1000);
      } else {
        setChatId('');
        setChatNanoId('');
        setMessages(initialMessages);
      }
    } else {
      setMessages(initialMessages);
    }
  }, [initialMessages]);

  useEffect(() => {
    const queryParams = new URLSearchParams(location.search);
    const { state } = location;
    if (
      !queryParams.get('chatId') &&
      !state?.msg &&
      messages.length == 0 &&
      appInfoInitialize?.welcome_text
    ) {
      setMessages([
        {
          text: appInfoInitialize.welcome_text,
          isUser: false,
        },
      ]);
    }
  }, [appInfoInitialize]);

  useEffect(() => {
    const { state } = location;
    const queryParams = new URLSearchParams(location.search);
    if (currentChatId || state?.msg || queryParams.get('chatId')) {
      return;
    }
    if (isMessageSend) {
      handleInterrupt();
      setTimeout(() => {
        setChatId('');
        setChatNanoId('');
        appInfoInitialize?.welcome_text &&
          setMessages([
            {
              text: appInfoInitialize?.welcome_text
                ? appInfoInitialize?.welcome_text
                : BrandingEnum.welcome_text,
              isUser: false,
            },
          ]);
      }, 1000);
    } else {
      setChatId('');
      setChatNanoId('');
      appInfoInitialize?.welcome_text &&
        setMessages([
          {
            text: appInfoInitialize?.welcome_text
              ? appInfoInitialize?.welcome_text
              : BrandingEnum.welcome_text,
            isUser: false,
          },
        ]);
    }
  }, [currentChatId]);

  useEffect(() => {
    if (initChatId) {
      setChatId(initChatId);
      setChatNanoId(initChatId);
    }
  }, [initChatId]);

  // const handleKeyDown = (e) => {
  //   setIsInputTyping(true);
  //   if (e?.key === 'Enter' && e?.keyCode === 13 && !e?.shiftKey) {
  //     e.preventDefault();

  //     if (!inputValue) {
  //       return;
  //     }

  //     handleSend();
  //   }
  // };

  const deleteChatMessage = (chatId: string, dataId: string) => {
    if (dataId && chatId && id) {
      chatService.chatDelete(chatId, dataId, id);
    }
  };

  const deleteMessage = (index: number) => {
    setMessages((prevMessages) => {
      const newMessages = [...prevMessages];
      deleteChatMessage(newMessages[index]?.dataId || '', newMessages[index]?.chatId || '');
      console.log(newMessages[index]);
      newMessages.splice(index, 1);
      if (index < newMessages.length && !newMessages[index].isUser) {
        deleteChatMessage(newMessages[index]?.dataId || '', newMessages[index]?.chatId || '');
        newMessages.splice(index, 1);
      }
      return newMessages;
    });
  };

  const reFreshAnswer = (index: number) => {
    if (isMessageSend) {
      messageApi.info('对话正在进行中，请稍后再试！');
      return;
    }
    if (index < 1) return;

    const questionText = messages[index - 1]?.text;

    setMessages((prevMessages) => {
      let newMessages = [...prevMessages];
      // newMessages.splice(index - 1, 2);

      for (let i = index - 1; i < newMessages.length; i++) {
        // console.log(111, newMessages[i]);
        if (newMessages[i]) {
          deleteChatMessage(newMessages[i].dataId || '', newMessages[i].chatId || '');
        }
      }

      thinkListcurrentMessageRef.current = [];

      newMessages.splice(index - 1);

      return newMessages;
    });

    setTimeout(() => {
      handleSend(questionText);
    }, 10);
  };

  const changeInputType = () => {
    setVoice(!voice);
  };

  const onVoiceStop = (text: string) => {
    setMessages((prevMessages) => {
      const lastMessage = prevMessages?.[prevMessages.length - 1];
      if (lastMessage && lastMessage.text === '语音识别中') {
        const newMessages = [...prevMessages];
        newMessages.pop();
        return newMessages;
      }
      return prevMessages;
    });
    if (isMessageSend) {
      handleInterrupt();
    }
    handleSend(text);
  };

  const textGenerateMsgAdd = () => {
    setMessages((prevMessages) => {
      const lastMessage = prevMessages?.[prevMessages.length - 1];
      if (lastMessage && lastMessage.isTextGenerate) {
        return prevMessages;
      }
      return [
        ...prevMessages,
        { text: '语音识别中', isUser: true, loading: true, isTextGenerate: true },
      ];
    });
  };

  const textGenerateMsgRemove = () => {
    setMessages((prevMessages) => {
      const lastMessage = prevMessages?.[prevMessages.length - 1];
      if (lastMessage && lastMessage.isTextGenerate) {
        const newMessages = [...prevMessages];
        newMessages.pop();
        return newMessages;
      }
      return prevMessages;
    });
  };

  const onSTT = (status: number) => {
    console.log('pppp');
    if (status == 0) {
      setIsMessageSend(true);
      setIsTextGenerate(true);
      textGenerateMsgAdd();
    }
    if (status == 1) {
      setIsMessageSend(true);
      setIsTextGenerate(false);
      textGenerateMsgRemove();
    }
    if (status == 2) {
      setIsMessageSend(false);
      setIsTextGenerate(false);
      textGenerateMsgRemove();
    }
  };

  useEffect(() => {
    if (isTextGenerate) {
      textGenerateMsgAdd();
    } else {
      textGenerateMsgRemove();
    }
  }, [isTextGenerate]);

  const onInterrupt = () => {
    // setIsTextGenerate(false)
    // handleInterrupt();
    if (isTextGenerate) {
      setIsTextGenerate(false);
      setIsMessageSend(false);
      // messageApi.info("语音识别已取消");
    } else {
      // handleInterrupt()
    }
    handleInterrupt();
  };

  const emitCard = (item) => {
    handleSend(item);
  };

  event$?.useSubscription((val) => {
    if (val.type === ChatEventType.SENDTEXT) {
      handleSend(val.data.toString());
    }
  });

  const [guessQuestions, setGuessQuestions] = useState<GuessQuestion[]>([]);

  const handleQuestionClick = (question: string) => {
    if (question) {
      // 直接发送用户点击的问题
      handleSend(question);
    }
  };

  const { voiceEnabled, suggestedQuestions, isInOrchestrationPage, variables, subAppDetail } =
    useOrchestrationStore();

  const flowVariables = useMemo(() => {
    if (!Array.isArray(variables)) {
      return {};
    }
    return variables.reduce(
      (acc: Record<string, any>, item: { key: string; defaultValue: any }) => {
        acc[item.key] = item.defaultValue;
        return acc;
      },
      {},
    );
  }, [variables]);

  useEffect(() => {
    if (!voiceEnabled && voice) {
      setVoice(false);
    }
  }, [voiceEnabled]);

  return (
    <div
      className="flex flex-col"
      style={{
        height: '100%',
        width: isMetaHuman || !isPc ? '100%' : '800px',
        margin: isMetaHuman || !isPc ? '0' : 'auto',
        // maxHeight: !isPc && isMobileSafari ? 'calc(100vh - 200px)' : undefined,
        // maxHeight: !isPc ? 'calc(100vh - 160px)' : undefined,
        // maxHeight: 'calc(100vh - 200px)',
      }}
    >
      {contextHolder}
      <MessageList
        messages={messages}
        robotAvatar={robotAvatar}
        username={username}
        colorPrimary={colorPrimary}
        isMetaHuman={isMetaHuman}
        isAudioPlaying={isAudioPlaying}
        isMuted={isMuted}
        isMessageSend={isMessageSend}
        isInputTyping={isInputTyping}
        deleteMessage={(index) => deleteMessage(index)}
        reFreshAnswer={(index) => reFreshAnswer(index)}
        handleSend={handleSend}
        emitCard={emitCard}
        guessQuestions={guessQuestions}
        onQuestionClick={handleQuestionClick}
      />
      <div
        className="flex items-center border-none px-2"
        style={
          !isPc
            ? {
                // position: 'fixed',
                bottom: '0',
                left: '0',
                right: '0',
                paddingTop: '20px',
                backgroundColor: '#EDEFF7',
                // border: '1px solid red',
              }
            : {
                backgroundColor: '#EDEFF7',
                paddingTop: '20px',
              }
        }
      >
        {voice == true ? (
          <FunasrRecorder
            isMessageSend={isMessageSend}
            onInterrupt={onInterrupt}
            onStop={(inputValue: string) => {
              console.log('isMessageSend', isMessageSend, inputValue);

              if (isMessageSend) {
                onInterrupt();
              }
              onVoiceStop(inputValue);
            }}
            onSTT={onSTT}
            onSwitch={changeInputType}
            className="flex h-full w-full items-center justify-center"
          />
        ) : (
          <div
            style={{
              borderRadius: '16px',
              border: '1px solid #e5e5e5',
              // padding: '5px',
              // padding: '0 5px',
              display: 'flex',
              alignItems: 'center',
              width: '100%',
              // height: '45px',
              backgroundColor: '#fff',
              position: 'relative',
              // marginLeft: isPc ? '0px' : '20px',
              // marginRight: isPc ? '0px' : '20px',
              // marginBottom: isPc ? '0px' : '20px',
            }}
          >
            {/* <MessageSendInputSmart
              handleSend={handleSend}
              changeInputType={changeInputType}
              handleInterrupt={handleInterrupt}
              isMessageSend={isMessageSend}
              voice={voice}
            /> */}

            <MessageSendInputHome
              handleSend={handleSend}
              changeInputType={changeInputType}
              handleInterrupt={handleInterrupt}
              isMessageSend={isMessageSend}
              isHome={false}
            ></MessageSendInputHome>
          </div>
        )}
      </div>
    </div>
  );
};

export default ChatBox;
